<template>
  <view>
    <canvas canvas-id="myCanvas" :style="{ width: canvasWidth + 'px', height: canvasHeight + 'px' }"></canvas>
    <button @click="saveToAlbum">保存到相册</button>
  </view>
</template>

<script>
export default {
  data() {
    return {
      canvasWidth: 600, // 根据需求调整
      canvasHeight: 400,
      tableData: {
        header: ['姓名', '年龄', '城市'],
        rows: [
          ['张三', 25, '北京'],
          ['李四', 30, '上海'],
          ['王五', 28, '广州']
        ]
      }
    };
  },
  methods: {
    drawTable() {
      const ctx = uni.createCanvasContext('myCanvas', this);
      const { header, rows } = this.tableData;
      const rowHeight = 40;
      const colWidth = this.canvasWidth / header.length;

      // 绘制表头
      ctx.setFillStyle('#f0f0f0');
      ctx.fillRect(0, 0, this.canvasWidth, rowHeight);
      ctx.setFontSize(16);
      ctx.setFillStyle('#333');
      header.forEach((text, index) => {
        ctx.fillText(text, colWidth * index + 10, 25);
      });

      // 绘制数据行
      rows.forEach((row, rowIndex) => {
        const y = (rowIndex + 1) * rowHeight;
        ctx.setFillStyle(rowIndex % 2 === 0 ? '#fff' : '#f9f9f9');
        ctx.fillRect(0, y, this.canvasWidth, rowHeight);
        ctx.setFillStyle('#666');
        row.forEach((cell, colIndex) => {
          ctx.fillText(cell, colWidth * colIndex + 10, y + 25);
        });
      });

      // 绘制边框
      ctx.setStrokeStyle('#ddd');
      ctx.setLineWidth(1);
      // 水平线
      for (let i = 0; i <= rows.length + 1; i++) {
        ctx.moveTo(0, i * rowHeight);
        ctx.lineTo(this.canvasWidth, i * rowHeight);
      }
      // 垂直线
      for (let i = 0; i <= header.length; i++) {
        ctx.moveTo(i * colWidth, 0);
        ctx.lineTo(i * colWidth, (rows.length + 1) * rowHeight);
      }
      ctx.stroke();

      ctx.draw(); // 绘制到画布
    },

    async saveToAlbum() {
      // 确保绘制完成
      await new Promise(resolve => setTimeout(resolve, 200));
      // 生成临时图片路径
      uni.canvasToTempFilePath({
        canvasId: 'myCanvas',
        success: (res) => {
          // 保存到相册
          uni.saveImageToPhotosAlbum({
            filePath: res.tempFilePath,
            success: () => uni.showToast({ title: '保存成功' }),
            fail: () => uni.showToast({ title: '保存失败', icon: 'none' })
          });
        },
        fail: (err) => console.error('生成图片失败:', err)
      });
    }
  },
  mounted() {
    this.drawTable();
  }
};
</script>

<style>

</style>
